<template>
  <van-popup
    v-model:show="show"
    position="bottom"
    round
    :style="{ height: '30%' }"
  >
    <van-datetime-picker
      v-model="currentDate"
      type="year-month"
      title="选择年月"
      :formatter="formatter"
      @confirm="confirm"
      @cancel="cancel"
    />
  </van-popup>
</template>

<script>
import { reactive, toRefs } from 'vue'
import dayjs from 'dayjs'
export default {
  name: 'PopMonth',
  props: {
    selectTime: {
      type: Function
    }
  },
  setup(props, { emit }) {
    const state = reactive({
      show: false,
      currentDate: new Date()
    })
    const formatter = (type, val) => {
      if (type === 'year') {
        return `${val}年`
      } else if (type === 'month') {
        return `${val}月`
      }
      return val
    }
    const toggle = () => {
      state.show = !state.show
    }
    const confirm = (val) => {
      state.show = false
      emit('selectTime', dayjs(val).format('YYYY-MM'))
    }
    const cancel = () => {
      state.show = false
    }
    return {
      formatter,
      toggle,
      confirm,
      cancel,
      ...toRefs(state)
    }
  }
}
</script>

<style lang="less" scoped></style>
